package com.hyfd.deal.Bill;

import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import com.hyfd.common.GenerateData;
import com.hyfd.common.utils.DateTimeUtils;
import com.hyfd.common.utils.MapUtils;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.dao.mp.ProductDao;
import com.hyfd.deal.BaseDeal;

public class E19BillDeal implements BaseDeal{

	Logger log = Logger.getLogger(getClass());
	
	@Autowired
	ProductDao productDao;
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> deal(Map<String, Object> order) {
		Map<String,Object> map = new HashMap<String,Object>();
		int flag = -1;
		try{
			String phone = (String) order.get("phone");//手机号
			double fee = (double) order.get("fee");//金额，以元为单位
			String curids = DateTimeUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS") + phone+GenerateData.getIntData(9, 2);
			map.put("orderId", curids);
			Map<String,Object> channel = (Map<String, Object>) order.get("channel");//获取通道参数
			String linkUrl = (String) channel.get("link_url");//充值地址
			String defaultParameter = (String) channel.get("default_parameter");//默认参数
			Map<String,String> paramMap = XmlUtils.readXmlToMap(defaultParameter.trim());
			String nowUpdate = paramMap.get("nowUpdate");
			String agentId = paramMap.get("agentId");
			String merchantKey = paramMap.get("merchantKey");
			String source = paramMap.get("source");
			String returnType = paramMap.get("returnType");
			String directFillUrl = paramMap.get("directFillUrl");//充值地址
			String accegmentUrl = paramMap.get("accegmentUrl");//号段查询地址
			String directSearchUrl = paramMap.get("directSearchUrl");//订单查询地址
			//号段验证
			String verifystring=getAccegmentVerify(agentId, source, phone, merchantKey);
			accegmentUrl+="?agentid="+agentId;
			accegmentUrl+="&source="+source;
			accegmentUrl+="&mobilenum="+phone;
			accegmentUrl+="&verifystring="+verifystring;
			log.error("19eaccegmentReq|"+accegmentUrl);
			String accegmentData=ToolHttp.get(false, accegmentUrl);
			Map<String, String> accegmentMap=getAccegmentReturnData(accegmentData);
			String carrierstypeName = accegmentMap.get("isptype");
			String belongzone = accegmentMap.get("provincename");
			Map<String,Object> productParam = new HashMap<String,Object>();
			productParam.put("prodContent", fee);
			productParam.put("prodIsptype", carrierstypeName);
			productParam.put("prodProvincedid", belongzone);
			productParam.put("prodType", "移动电话");
			Map<String,Object> product = productDao.selectAll(productParam).get(0);//获取产品
			String prodId = product.get("prod_id")+"";//产品ID
			String backurl="";
			String orderid=curids; //30位
			String mobilenum=phone;
			String mark="";
			//准备充值请求参数
			verifystring=getDirectFillVerify(prodId, agentId, backurl, returnType, orderid, mobilenum,source, mark, merchantKey);
			directFillUrl+="?prodid="+prodId;
			directFillUrl+="&agentid="+agentId;
			directFillUrl+="&backurl="+backurl;
			directFillUrl+="&returntype="+returnType;
			directFillUrl+="&orderid="+orderid;
			directFillUrl+="&mobilenum="+mobilenum;
			directFillUrl+="&source="+source;
			directFillUrl+="&mark="+mark;
			directFillUrl+="&verifystring="+verifystring;
			//发送充值请求
			String directFillData = ToolHttp.get(false, directFillUrl);
			if(directFillData!=null&&!directFillData.equals("")){
				Map<String,String> resultMap = XmlUtils.readXmlToMap(directFillData);//解析XML
				String resultNo = resultMap.get("resultno");
				map.put("resultCode", resultNo);
				if(resultNo.equals("0000")){//提交成功
					flag = 1;
				}if(resultNo.equals("1006")||resultNo.equals("0002")){//扣款状态未知
					flag = -1;
				}else{
					flag = 0;
				}
			}
		}catch(Exception e){
			log.error("19易充值出错"+e.getMessage()+"||"+MapUtils.toString(order));
		}
		map.put("status", flag);
		return map;
	}

	public static String getDirectFillVerify(String prodid,String agentid,String backurl,String returntype,String orderid,String mobilenum,String source,String mark,String merchantKey){
		StringBuilder sb=new StringBuilder();
		sb.append("prodid="+prodid);
		sb.append("&agentid="+agentid);
		sb.append("&backurl="+backurl);
		sb.append("&returntype="+returntype);
		sb.append("&orderid="+orderid);
		sb.append("&mobilenum="+mobilenum);
		sb.append("&source="+source);
		sb.append("&mark="+mark);
		sb.append("&merchantKey="+merchantKey);
		return getKeyedDigest(sb.toString(),"");
	}
	
	public static Map<String,String> getAccegmentReturnData(String xml) throws Exception{
		Map<String, String> rm=new HashMap<String, String>();
		Document doc = DocumentHelper.parseText(xml);
		Element rootElt = doc.getRootElement(); 
		Iterator<?> it = rootElt.elementIterator();
		while (it.hasNext()) {
			Element recordEle = (Element) it.next();
			List<?> elList=recordEle.elements();
			for(int i=0;i<elList.size();i++){
				Element el=(Element) elList.get(i);
				rm.put(el.attributeValue("name"), URLDecoder.decode(el.attributeValue("value"),"utf-8"));
			}
		}
		return rm;
	}
	
	public static String getDirectProductVerify(String agentid,String source,String merchantKey){
		StringBuilder sb=new StringBuilder();
		sb.append("agentid="+agentid);
		sb.append("&source="+source);
		sb.append("&merchantKey="+merchantKey);
		return getKeyedDigest(sb.toString(),"");
	}
	
	public static String getAccegmentVerify(String agentid,String source,String mobilenum,String merchantKey){
		StringBuilder sb=new StringBuilder();
		sb.append("agentid="+agentid);
		sb.append("&source="+source);
		sb.append("&mobilenum="+mobilenum);
		sb.append("&merchantKey="+merchantKey);
		return getKeyedDigest(sb.toString(),"");
	}
	
	/**
	 * MD5加密
	 * @author lks 2017年1月12日下午3:00:56
	 * @param strSrc
	 * @param key
	 * @return
	 */
	public static String getKeyedDigest(String strSrc, String key) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(strSrc.getBytes("UTF8"));
            
            String result="";
            byte[] temp;
            temp=md5.digest(key.getBytes("UTF8"));
    		for (int i=0; i<temp.length; i++){
    			result+=Integer.toHexString((0x000000ff & temp[i]) | 0xffffff00).substring(6);
    		}
    		
    		return result;
    		
        } catch (NoSuchAlgorithmException e) {
        	
        	e.printStackTrace();
        	
        }catch(Exception e)
        {
          e.printStackTrace();
        }
        return null;
    }
}
